home *** CD-ROM | disk | FTP | other *** search
/ Windows News 2010 Summer - Disc 1 / WN_Ete2010_CD1.iso / Onglet5 / Weezo / Weezo setup.exe / {code_appDir} / www / includes / mySQLFunctions.php < prev    next >
PHP Script  |  2010-05-19  |  10KB  |  317 lines

  1. <?php
  2. /**
  3.  * MySQL database creation / connection
  4.  *
  5.  * PHP version 5
  6.  *
  7.  * LICENSE: This source file is subject to version 3.0 of the PHP license
  8.  * that is available through the world-wide-web at the following URI:
  9.  * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
  10.  * the PHP License and are unable to obtain it through the web, please
  11.  * send a note to license@php.net so we can mail you a copy immediately.
  12.  *
  13.  * @category   NA
  14.  * @package    NA
  15.  * @author     Nicolas Bruley / Peer 2 World <contact@weezo.net>
  16.  * @copyright  2005-2009 Nicolas Bruley / Peer 2 World
  17.  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
  18.  * @version    CVS: $Id:$
  19.  * @link       http://www.weezo.net
  20.  * @since      File available since Release 1.0.1
  21.  */
  22.  
  23.  
  24. /**
  25.  * @desc Initialize MySQL database for a Weezo resource
  26.  *          If needed, Generate database, generate, set and save root password
  27.  * @param string $databaseName: name of database to create. Resource ID will be automatically appened
  28.  *
  29.  * @return mixed: result, true if database was created and all is OK, database name if database newly created, false if error
  30.  */
  31. function mySQLInit($databaseName){
  32.     // Add resource id to database name (except for root)
  33.     $databaseName=mySQLDatabase($databaseName);
  34.  
  35.     // Check MySQL existence and databasename
  36.     if($databaseName=='root' || !file_exists(cfAppDataRootDir().'/MySQL/bin/mysqld.exe') || !mySQLValidName($databaseName)) return false;
  37.  
  38.     // If passwords file doesn't exist, init database
  39.     if(!file_exists(cfAppDataRootDir().'/MySQL/MySQL.ini')){if(!mySQLInitRoot()) return false;}
  40.  
  41.     // Load stored password
  42.     $passwords=parse_ini_file(cfAppDataRootDir().'/MySQL/MySQL.ini');
  43.  
  44.     // If password set, db (should be) OK
  45.     if(isset($passwords[$databaseName])) {
  46.         
  47.         $checked=cfMGetVar('weezoMySQLDatabasesChecked');
  48.         if(isset($checked[$databaseName])) return true;
  49.         
  50.         // Check that database exists
  51.         mySQLConnectDB('root');
  52.         $result=mysql_query('SHOW DATABASES');
  53.         while ($row = mysql_fetch_assoc($result)) {
  54.             if(@$row['Database']==$databaseName) {
  55.                 // Set as checked (cache result)
  56.                 $checked[$databaseName]=1;
  57.                 cfMSetVar('weezoMySQLDatabasesChecked',$checked);
  58.                 return true;
  59.             }
  60.         }
  61.     }
  62.  
  63.     // Generate password
  64.     $password=cfGenerateID(16);
  65.     $passwords[$databaseName]=$password;
  66.  
  67.     // Connect as root user
  68.     mySQLConnectDB('root');
  69.  
  70.     // Create database and user
  71.     mysql_select_db('mysql');
  72.     mysql_query("CREATE DATABASE IF NOT EXISTS ".$databaseName." ;");
  73.     mysql_query("CREATE USER ".$databaseName."@localhost IDENTIFIED BY '".$password."';");
  74.     mysql_query("GRANT USAGE ON * . * TO ".$databaseName."@localhost IDENTIFIED BY '".$password."' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;");
  75.     mysql_query("GRANT ALL PRIVILEGES ON ".$databaseName.".* TO ".$databaseName."@localhost WITH GRANT OPTION");
  76.     mysql_query('FLUSH PRIVILEGES');
  77.     mysql_close();
  78.     // Save password to file
  79.     mySQLWritePasswords($passwords);
  80.  
  81.     return $databaseName;
  82. }
  83.  
  84. /**
  85.  * @desc Display MySQL table
  86.  *
  87.  * @param string $table: table name
  88.  */
  89. function mySQLDisplayTable($table){
  90.     if(is_array($table)){
  91.         $result=$table;
  92.     }
  93.     else{
  94.         $query='SELECT * FROM '.$table;
  95.         $result=mysql_query($query);
  96.         echo "<b>".$table.'</b><br>';
  97.     }
  98.  
  99.     if(!$result || mysql_num_rows($result)==0) echo 'Table vide<br/><br/>';
  100.     else{
  101.         echo '<table style="border:1px solid black; color:#550; font-family:arial; font-size:10px" cellspacing=0 cellpadding=0><tr>';
  102.  
  103.         $rowNb=0;
  104.  
  105.         echo '</tr>';
  106.         while ($row = mysql_fetch_assoc($result)) {
  107.             echo '<tr>';
  108.             if($rowNb==0) {
  109.                 foreach ($row as $key=>$value) echo '<td style="font-weight:bold; padding:3px; background:#550; color:white; font-weight:bold; font-family:arial; font-size:10px">'.$key.'</td>';
  110.                 echo '</tr>';
  111.             }
  112.             foreach ($row as $k2=>$v2) {
  113.                 echo '<td style="border:1px dashed #AAA; padding:3px">';
  114.                  if($k2=='ts') echo date('d/m/y h:i:s',$v2); else echo $v2;
  115.                 echo '</td>';
  116.             }
  117.             echo "</tr>\n";
  118.             $rowNb++;
  119.         }
  120.         echo "</table>\n";
  121.     }
  122. }
  123.  
  124. /**
  125.  * @desc Destroy a MySQL database and user
  126.  *
  127.  * @param string $resId : unique resource id
  128.  * @return boolean result
  129.  */
  130. function mySQLDestroyResource($resId){
  131.     mySQLConnectDB('root');
  132.     mysql_select_db('mysql');
  133.  
  134.     $dbIds=explode("\n",@file_get_contents(cfAppDataRootDir().'/MySQL/MySQL.ini'));
  135.     foreach ($dbIds as $nb=>$line) if(strpos($line,$resId)){
  136.         unset($dbIds[$nb]);
  137.         $dbId=substr($line,0,strpos($line,'='));
  138.         // Destroy user
  139.         mysql_query("DROP USER '".$dbId."'@'localhost'");
  140.  
  141.         // Destroy database
  142.         mysql_query("DROP DATABASE IF EXISTS `".$dbId."`");
  143.         // Clean passwords file
  144.         file_put_contents(cfAppDataRootDir().'/MySQL/MySQL.ini',join("\n",$dbIds));
  145.         mysql_close();
  146.         return true;
  147.     }
  148.     mysql_close();
  149.     return false;
  150. }
  151.  
  152. /**
  153.  * @desc return resource unique Id :    if resource env is set, return cfRGetVar('id'),
  154.  *                                         else parse resource config data and return id entry
  155.  *
  156.  * @return string : resource unique Id
  157.  */
  158. function mySQLUniqueResourceId(){
  159.     // Return resource ID
  160.     if(isset($_SESSION['activeResourceId'])) return cfRGetVar('id');
  161.     // for extensions that use their own session, use stored weezo session to retreive id
  162.     elseif(isset($_ENV['weezoSession']['res'][$_ENV['weezoSession']['activeResourceId']]['id'])) return $_ENV['weezoSession']['res'][$_ENV['weezoSession']['activeResourceId']]['id'];
  163.     elseif(cfGGetVar('configResourceUniqueId')) return cfGGetVar('configResourceUniqueId');
  164.     elseif(@$_ENV['resourceConfigFilename'] || cfGGetVar('resourceConfigFilename')){
  165.         $resourceConfigFilename=((isset($_ENV['resourceConfigFilename']))?$_ENV['resourceConfigFilename']:cfGGetVar('resourceConfigFilename'));
  166.         if(!($resData=cfParse_ini_file(cfAppDataDir().'/'.$resourceConfigFilename))) return false;
  167.         if(!isset($resData['id'])) return false;
  168.         else {
  169.             cfGSetVar('configResourceUniqueId',$resData['id']);
  170.             return $resData['id'];
  171.         }
  172.     }
  173.     else return false;
  174. }
  175.  
  176. /**
  177.  * @desc Called on MySQL server connection error
  178.  *         Display error page
  179.  *
  180.  */
  181. function connectionError($err=false){
  182.     global $w_lng;
  183.     require_once(INCLUDE_DIR.'outputFunctions.php');
  184.     outDisplayErrorPage('MySQL connection error: '.$err,false,true);
  185. }
  186.  
  187. /**
  188.  * @desc write mysql users/passwords in mysql/mysql.ini file
  189.  *
  190.  * @param array $passwords
  191.  * @return boolean result
  192.  */
  193. function mySQLWritePasswords($passwords){
  194.     if (!$fp = fopen(cfAppDataRootDir().'/MySQL/MySQL.ini', 'w')) return false;
  195.     foreach ($passwords as $key=>$value) fwrite($fp,$key.'='.$value."\n");
  196.     fclose($fp);
  197. }
  198. function mySQLValidName($name){
  199.     return true;
  200. }
  201.  
  202. /**
  203.  * @desc Initialize MySQL for Weezo
  204.  *         Generate, set and save root password
  205.  * @param boolean $changePassword : set to true to renew with randmo password or to new password value
  206.  *
  207.  * @return boolean : result : true if MySQL present and correctly configured
  208.  */
  209. function mySQLInitRoot($changePassword=false){
  210.     // Check MySQL existence
  211.     if(!file_exists(cfAppDataRootDir().'/MySQL/bin/mysqld.exe')) return false;
  212.  
  213.     // Load stored password
  214.     if(file_exists(cfAppDataRootDir().'/MySQL/MySQL.ini')) $passwords=parse_ini_file(cfAppDataRootDir().'/MySQL/MySQL.ini');
  215.     else $passwords=false;
  216.  
  217.     // Check stored password
  218.     if(isset($passwords['root']) && strlen($passwords['root'])){
  219.         if(!$socket=@fsockopen('127.0.0.1',mySQLPort(),$errno, $errstr, 3)) connectionError('connection failed (1)'); else fclose($socket);
  220.         if(mysql_connect('localhost','root',$passwords['root'])){
  221.             mysql_close();
  222.             if(!$changePassword) return true;
  223.             $password=$passwords['root'];
  224.         }
  225.         else $password='';
  226.     }
  227.     else $password='';
  228.     // Try to connect to MySQL server with blank password
  229.     if(!$socket=@fsockopen('127.0.0.1',mySQLPort(),$errno, $errstr, 3)) connectionError('connection failed (2)'); else fclose($socket);
  230.     if(!mysql_connect('localhost','root',$password)) return false;
  231.     // Connect mysql database
  232.     if(!mysql_select_db('mysql')) return false;
  233.     // Set new password
  234.     if(!$password || $changePassword===true) $password=md5(rand(0,9999999999).microtime(true)); else $password=$changePassword;
  235.  
  236.     // Save and set password
  237.     $passwords['root']=$password;
  238.     if(mysql_query('SET PASSWORD FOR root@localhost=PASSWORD("'.$password.'")')){
  239.         mySQLWritePasswords($passwords);
  240.         mysql_query('FLUSH PRIVILEGES');
  241.     }
  242.     mysql_query("DROP USER ``@`%`");
  243.     mysql_close();
  244.     return true;
  245. }
  246.  
  247.  
  248. /**
  249.  * @desc return host for MySQL connection
  250.  *
  251.  * @return string : host name
  252.  */
  253. function mySQLHost($database=false){
  254.     return 'localhost';
  255. }
  256.  
  257. /**
  258.  * @desc return port for MySQL database
  259.  *
  260.  * @return string : port number
  261.  */
  262. function mySQLPort($database=false){return '3306';}
  263.  
  264. /**
  265.  * @desc return user name for MySQL database
  266.  *
  267.  * @return string : user name
  268.  */
  269. function mySQLUser($database){
  270.     if($database=='root') return $database;
  271.  
  272.     // Get resource unique Id
  273.     if(!($ruid=mySQLUniqueResourceId())) return false;
  274.     return strtolower(substr($database.$ruid,0,16));
  275. }
  276.  
  277. /**
  278.  * @desc return database name for MySQL connection
  279.  *
  280.  * @return string : user name
  281.  */
  282. function mySQLDatabase($database){return mySQLUser($database);}
  283.  
  284. /**
  285.  * @desc return user password for MySQL connection
  286.  *
  287.  * @return string : password
  288.  */
  289. function mySQLPassword($database){
  290.     if(!$database) return false;
  291.     if(!file_exists(cfAppDataRootDir().'/MySQL/MySQL.ini')) {
  292.         require_once(INCLUDE_DIR.'outputFunctions.php');
  293.         outDisplayErrorPage(cfCaption('extMySQLRequired'));
  294.     }
  295.     $passwords=parse_ini_file(cfAppDataRootDir().'/MySQL/MySQL.ini');
  296.     if(isset($passwords[mySQLDatabase($database)])) return $passwords[mySQLDatabase($database)];
  297.     return false;
  298. }
  299.  
  300. /**
  301.  * @desc Connect and select a database
  302.  *
  303.  * @return boolean
  304.  */
  305. function mySQLConnectDB($database){
  306.     if(!$socket=@fsockopen('127.0.0.1',mySQLPort(),$errno, $errstr, 3)) connectionError('connection failed (3)'); else fclose($socket);
  307.  
  308.     if(!mysql_connect($host=mySQLHost($database),$user=mySQLUser($database),mySQLPassword($database))) return false;
  309.  
  310.     if($database=='root') return true;
  311.     if(!mysql_select_db(mySQLDatabase($database))){
  312.         mysql_close();
  313.         return false;
  314.     }
  315.     return true;
  316. }
  317. ?>